import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

public class MyHashMap<K,V>{
    private static  final int DEFAULT_SIZE=16;
    private Entry<K,V> [] data;
    private int size;
    private int capacity;

    public MyHashMap() {
        this(DEFAULT_SIZE);
    }

    public MyHashMap(int capacity){
        if(capacity > 0){
            data = new Entry[capacity];
            size = 0;
            this.capacity = capacity;
        }
    }

    private int hash(K key){
        int h = 0;
        if(key == null) h = 0;
        else{
            h = key.hashCode() ^ (h >>> 16);
        }
        return h%capacity;
    }

    public void put(K key,V value){
        if(key == null){
            System.out.println("error");
        }
        int hash = hash(key);
        System.out.println("put hash = " + hash);
        Entry<K,V> nE = new Entry<>(key,value,null);
        Entry<K,V> mE = data[hash];
        while(mE != null){
            if(mE.key.equals(key)){
                mE.value = value;
                return ;
            }
            mE = mE.next;
        }

        nE.next = data[hash];
        data[hash] = nE;
        size ++;
    }

    public V get(K key ){
        if(key == null){
            System.out.println("error");
        }
        int hash = hash(key);
        Entry<K,V> entry = data[hash];
        while(entry != null){
            if(entry.key.equals(key)){
                return entry.value;
            }
        }
        return null;
    }

    private class Entry<K,V>{
        K key;
        V value;
        Entry<K,V> next;

        public Entry(K key, V value, Entry<K, V> next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }

    public static void main(String[] args) {
//        MyHashMap<String,String> map = new MyHashMap<>();
//        map.put("11","aaa");
//        map.put("djfdjljf","aabbb");
//        map.put("jdkfjdlkfj","aabbbcc");
//        System.out.println(map.get("22"));

       Map<String,String> table = new Hashtable<>();
        table.put("1","first");
//        table.put("1",null);//出异常

        table  = new HashMap<>();
        table.put("1",null);
        table.put(null,null);
        table.put(null,"1223");
        System.out.println(table.get(null));
    }
}
